package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.dtos.IsPassDto;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsClientService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
@Slf4j
public class WmNewsClientServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsClientService {

    private final WmNewsMapper wmNewsMapper;

    private final WmUserMapper wmUserMapper;

    @Override
    public PageResponseResult findList(NewsAuthDto dto) {
        log.info("dto:{}",dto);
        Page<WmNews> pg = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(dto.getStatus()!=null,WmNews::getStatus,dto.getStatus());
        lambdaQueryWrapper.like(dto.getTitle()!= "",WmNews::getTitle,dto.getTitle());
        List<WmNews> records = page(pg,lambdaQueryWrapper).getRecords();
        log.info("records:{}",records);
        for (WmNews record : records) {
            Integer id = record.getUserId();
            WmUser wmUser = wmUserMapper.selectById(id);
            record.setAuthorName("admin");
        }
        PageResponseResult result = new PageResponseResult();
        result.setSize(dto.getSize());
        result.setCurrentPage(dto.getPage());
        result.setTotal((int) pg.getTotal());
        result.setData(JSON.toJSONString(records));

        String jsonString = JSON.toJSONString(records);

        return result;
    }

    @Override
    public ResponseResult findOne(Integer id) {
        WmNews news = wmNewsMapper.selectById(id);
        Integer userId = news.getUserId();
        news.setAuthorName(wmUserMapper.selectById(userId).getName());
        return ResponseResult.okResult(news);
    }

    @Override
    public ResponseResult isPass(IsPassDto dto) {
        WmNews news = wmNewsMapper.selectById(dto.getId());
        news.setStatus(dto.getStatus());
        if(dto.getMsg()!=null){
            news.setReason(dto.getMsg());
        }
        wmNewsMapper.updateById(news);
        return ResponseResult.okResult(null);
    }
}
